package io.renren.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.Constant;
import io.renren.modules.sys.dao.MySysMenuDao;
import io.renren.modules.sys.entity.MySysMenuEntity;
import io.renren.modules.sys.entity.SysMenuEntity;
import io.renren.modules.sys.service.MySysMenuService;
import io.renren.modules.sys.service.MySysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * @author ifredom
 * @description 针对表【sys_menu(菜单管理)】的数据库操作Service实现
 * @createDate 2022-04-20 21:47:14
 */
@Service
public class MySysMenuServiceImpl extends ServiceImpl<MySysMenuDao, MySysMenuEntity>
        implements MySysMenuService {

    @Autowired
    private MySysUserService mySysUserService;

    @Override
    public List<MySysMenuEntity> getUserMenuList(Long userId) {
        if (userId == Constant.SUPER_ADMIN) {
            return getMenuList(null);
        }
        List<Long> menuIdList = mySysUserService.queryAllMenuId(userId);
        return getMenuList(menuIdList);
    }

    private List<MySysMenuEntity> getMenuList(List<Long> menuIdList) {
        // 查询拥有的所有菜单
        List<MySysMenuEntity> menus = this.baseMapper.selectList(new QueryWrapper<MySysMenuEntity>()
                .in(Objects.nonNull(menuIdList), "menu_id", menuIdList).in("type", 0, 1));
        // 将id和菜单绑定
        HashMap<Long, MySysMenuEntity> menuMap = new HashMap<>(12);
        for (MySysMenuEntity s : menus) {
            menuMap.put(s.getMenuId(), s);
        }
        Iterator<MySysMenuEntity> iterator = menus.iterator();

        while (iterator.hasNext()) {
            MySysMenuEntity menu = iterator.next();
            MySysMenuEntity parent = menuMap.get(menu.getParentId());
            if (Objects.nonNull(parent)) {
                parent.getList().add(menu);
                iterator.remove();
            }
        }

        return menus;

    }
}
